package com.dlm.sdk.api;

import com.alibaba.fastjson.JSONObject;
import com.dlm.sdk.kit.ParaMap;
import com.jfinal.kit.HttpKit;
import org.apache.commons.lang.StringUtils;

import java.util.Map;

/**
 * Created by 宋冲 on 15/3/26.
 * chong.song@alibaba-inc.com
 */
public class OpenIdApi {
    private static String url = "https://api.weixin.qq.com/sns/oauth2/access_token?grant_type=authorization_code";

    public static String getOpenIdByCode(String code){
        ApiConfig ac = ApiConfigKit.getApiConfig();
        String appId = ac.getAppId();
        String appSecret = ac.getAppSecret();
        Map<String, String> queryParas = ParaMap.create("appid", appId)
                .put("secret", appSecret)
                .put("code",code).getData();
        String json = HttpKit.get(url, queryParas);
        if (StringUtils.isNotBlank(json) && json.contains("openid")) {
            JSONObject parse = JSONObject.parseObject(json);
            if(parse != null) {
                return (String)parse.get("openid");
            }
        }
        return null;
    }

}
